from django_filters import rest_framework as filters
from rest_framework import viewsets

from .models import Movie, Category
from .permissions import IsAdminUserOrReadOnly
from .serializers import MovieSerializer, CategorySerializer


class MovieFilter(filters.FilterSet):
    movie_name = filters.CharFilter(lookup_expr='icontains')
    category_id = filters.NumberFilter()
    region = filters.NumberFilter()

    class Meta:
        model = Movie
        fields = ['movie_name', 'category_id', 'region']


class MovieViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    # filterset_fields = ('movie_name',)  # 完整查询
    filterset_class = MovieFilter
    permission_classes = [IsAdminUserOrReadOnly, ]


class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all().order_by('id')
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUserOrReadOnly, ]
